package com.itheima.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomException;
import com.itheima.entity.*;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    //    用户下单
    @Override
    public void submit(Orders orders) {
        //1.获取当前用户的id
        Long currentId = BaseContext.getCurrentId();

        //2-1.根据id查购物车数据shoppingCart
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
//        防止异常
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }
        //2-2.根据id查用户数据user
        User user = userService.getById(currentId);

        //2-3.根据id查地址数据addressBook
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
//        防止异常
        if (addressBook == null) {
            throw new CustomException("地址信息有误，不能下单");
        }

        //3.插入数据到订单表（一条）
        long orderId = IdWorker.getId();

        //用原子类计算总金额（多线程，高并发都不会错）
        AtomicInteger amount = new AtomicInteger();
//
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
//            累加金额：金额*分数 在累加
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        orders.setId(orderId);
        orders.setUserName(user.getName());//订单号
        orders.setUserId(currentId);//用户
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);//待派送
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setNumber(String.valueOf(orderId));

        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());
        //地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //插入order表
        this.save(orders);


        //4.向订单明细表插入数据（可能多条）
        orderDetailService.saveBatch(orderDetails);

        //5.清空购物车数据
        shoppingCartService.remove(queryWrapper);


    }

    @Override
    public List<OrderDetail> getOrderDetailListByOrderId(Long orderId) {

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        //根据order表的条件查询出order_detail的数据，因为一个订单可能有多条菜品数据
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        return orderDetailList;

    }
}
